package com.gwsdk.paysdk.acitvityV2.dialog;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.gwsdk.paysdk.acitvityV2.adapter.GWSmallAccountAdapter;
import com.gwsdk.paysdk.bean.LoginModel;
import com.gwsdk.paysdk.bean.PersonalCenterModel;
import com.gwsdk.paysdk.bean.SdkDomain;
import com.gwsdk.paysdk.callback.AddAccountCallback;
import com.gwsdk.paysdk.common.Constant;
import com.gwsdk.paysdk.dialog.AddAccountDialog;
import com.gwsdk.paysdk.dialog.GWTipDialog;
import com.gwsdk.paysdk.entity.UserLogin;
import com.gwsdk.paysdk.http.process.AddSmallAccountProgress;
import com.gwsdk.paysdk.http.process.SmallAccountLoginProgress;
import com.gwsdk.paysdk.utils.GWInflaterUtils;
import com.gwsdk.paysdk.utils.GWLog;
import com.gwsdk.paysdk.utils.SharedPreferencesUtils;
import com.gwsdk.paysdk.utils.TextUtils;
import com.gwsdk.paysdk.utils.ToastUtil;
import com.gwsdk.paysdk.view.round.NiceImageView;
import com.lidroid.xutils.BitmapUtils;

import java.util.List;



public class GWChooseAccountDialog extends DialogFragment {


    private static final String TAG = "GWChooseAccountDialog";

    private Activity activity;

    private NiceImageView avatarImage;
    private TextView userName;
    private TextView switchAccount;
    private ListView smaleAccountListView;
    private UserLogin userLogin;
    private BitmapUtils bitmapUtils;
    private GWTipDialog mcTipDialog;
    private ImageView rememberImage;
    private List<UserLogin.SmallAccountEntity> smallAccountList;
    private TextView addAccount;
    private GWSmallAccountAdapter adapter;

    private Boolean isRemember = false;

    private AddAccountDialog.addAccountBuilder dialogBuilder;

    public GWChooseAccountDialog() {

    }

    @SuppressLint("ValidFragment")
    public GWChooseAccountDialog(Activity activity,UserLogin userLogin){
        this.activity = activity;
        this.userLogin = userLogin;
        this.smallAccountList = userLogin.getSmallAccountList();
        bitmapUtils = new BitmapUtils(activity);
    }

    private Boolean isLogin = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(GWInflaterUtils.getLayout(activity,"gw_dialog_choose_account"), container, false);

        avatarImage = view.findViewById(GWInflaterUtils.getControl(activity,"avatar"));
        userName = view.findViewById(GWInflaterUtils.getControl(activity,"user_name"));
        rememberImage = view.findViewById(GWInflaterUtils.getControl(activity,"remember"));
        userName.setText(userLogin.getNickname());
        avatarImage.setCornerRadius(30);
        addAccount = view.findViewById(GWInflaterUtils.getControl(activity,"add_account"));
        if (userLogin.getUserIcon() != null && !userLogin.getUserIcon().isEmpty()){
            bitmapUtils.display(avatarImage,userLogin.getUserIcon());
        }else {
            if(!com.gwsdk.paysdk.utils.TextUtils.isEmpty(Constant.SDK_LOGO_URL)){
                bitmapUtils.display(avatarImage, Constant.SDK_LOGO_URL );
            }
        }



        addAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (smallAccountList.size()>=10){
                    ToastUtil.show(getActivity(),"小号个数已满10，不可继续添加");
                }else {
                    dialogBuilder = new AddAccountDialog.addAccountBuilder().setSureClick(clickcallback);
                    dialogBuilder.show(getActivity(), getFragmentManager());
                }
            }
        });

        rememberImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        smaleAccountListView = view.findViewById(GWInflaterUtils.getControl(activity,"listView"));
        adapter = new GWSmallAccountAdapter(activity);
        adapter.setLoginUser(userLogin);
        smaleAccountListView.setAdapter(adapter);
        smaleAccountListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isLogin == false){
                    isLogin = true;
                    smallAccountLogin(smallAccountList.get(position).getSmallUserId());
                }
            }
        });
        if (smallAccountList.size()>0){
            adapter.setListData(smallAccountList);
        }
        return view;
    }


    /**
     * 添加小号弹窗确认按钮点击事件
     */
    AddAccountCallback clickcallback = new AddAccountCallback() {
        @Override
        public void addAccount(String Account) {
            if (TextUtils.isEmpty(Account)){
                ToastUtil.show(getActivity(),"小号名不能为空");
                return;
            }

            dialogBuilder.closeDialog(getFragmentManager());
            mcTipDialog = new GWTipDialog.Builder().setMessage("请稍等...").show(getActivity(),getFragmentManager());
            AddSmallAccountProgress addSmallAccountProgress = new AddSmallAccountProgress();
            addSmallAccountProgress.setSmaleNickname(Account.trim());
            addSmallAccountProgress.setUserId(PersonalCenterModel.getInstance().getUserId());
            addSmallAccountProgress.setGameId(SdkDomain.getInstance().getGameId());
            addSmallAccountProgress.post(mHandler);
        }
    };

    private String loginSmallId = "";
    private void smallAccountLogin(String smallID){
        loginSmallId = smallID;
        SmallAccountLoginProgress progress = new SmallAccountLoginProgress();
        progress.setSmallUserId(smallID);
        progress.setUserId(userLogin.getAccountUserId());
        progress.setGameId(SdkDomain.getInstance().getGameId());
        progress.setYKLogin(userLogin.isYKLogin());
        progress.setToken(userLogin.getToken());
        progress.ageStatus = userLogin.getAgeStatus();
        progress.birthday = userLogin.getBirthday();
        progress.post(mHandler);
        mcTipDialog = new GWTipDialog.Builder().setMessage("进入游戏...").show(activity,getFragmentManager());
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isLogin = false;
            if (null != mcTipDialog) {
                mcTipDialog.dismiss();
            }
            switch (msg.what) {
                case Constant.ADD_SMALL_ACCOUNT_SUCCESS:  //添加小号成功
                    UserLogin login = (UserLogin)msg.obj;
                    smallAccountList = login.getSmallAccountList();
                    adapter.setListData(smallAccountList);
                    ToastUtil.show(getActivity(), "添加成功");
                    break;
                case Constant.SMALL_ACCOUNT_LOGIN_SUCCESS:  //小号登录成功
                    UserLogin smallAccountLogin = (UserLogin) msg.obj;
                    LoginModel.instance().smallAccountLoginSuccess(smallAccountLogin);
                    SharedPreferencesUtils.getInstance().setLastLoginID(activity,loginSmallId);
                    dismissAllowingStateLoss();
                    break;
                case Constant.SMALL_ACCOUNT_LOGIN_FAIL:  //小号登录失败
                    String tip = (String) msg.obj;
                    ToastUtil.show(activity, tip);
                    LoginModel.instance().loginFail();
//                    btnPlay.setEnabled(true);
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置对话框的样式
        setStyle(STYLE_NO_FRAME, GWInflaterUtils.getIdByName(activity, "style", "gw_transparent"));
    }

    @SuppressLint("NewApi")
    @Override
    public void onStart() {
        // 1, 设置对话框的大小
        Window window = getDialog().getWindow();
        WindowManager wm = window.getWindowManager();
        Point windowSize = new Point();
        wm.getDefaultDisplay().getSize(windowSize);
        int width = windowSize.x;
        int height = windowSize.y;
        if (width >= height) {// 横屏
            window.getAttributes().width = (int) (windowSize.y * 0.85);
            window.getAttributes().height = (int) (windowSize.y * 0.88);
        } else {// 竖屏
            window.getAttributes().width = (int) (windowSize.x * 0.786);
            window.getAttributes().height = (int) (windowSize.x * 0.8138);
        }
        window.setGravity(Gravity.CENTER);
        super.onStart();
    }


    public void show(FragmentManager fm){
        if (fm == null) {
            GWLog.e(TAG, "show error : fragment manager is null.");
            return;
        }
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(this, TAG);
        ft.show(this);
        ft.commitAllowingStateLoss();
    }
}
